<?php
/**
 * Created by PhpStorm.
 * User: lan
 * Date: 2018/1/24
 * Time: 14:13
 */
namespace app\yunda\home;


use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order as EsOrder;
use app\yunda\model\Money_record;
use app\yunda\model\User;
use think\Exception;
use think\Request;
use think\Db;
use think\Loader;
use app\yunda\model\Zforder;
use app\yunda\model\Order;
use app\yunda\model\Brokerage;
use app\yunda\model\Member;
use app\yunda\model\Danhao;

/**
 * Class Pay微信支付
 * @package app\yunda\home
 */
class Pay extends Base {

    //小程序支付
    public function PayXcx(){
        $param=request()->only('openid,type,total_fee,id');

        if(empty($param['type'])) return mogo_error('支付分类不能为空');
        if(empty($param['id'])) return mogo_error('支付id不能为空');//具体支付什么

        if(empty($param['openid'])) return mogo_error('openid不才能为空',0);
        $user=User::get(['openid'=>$param['openid']]);
        if(!$user) return mogo_error('用户不存在',0);

        //小程序支付类传参处理
        $body='韵达快递';
        $param['total_fee']=0.01;
//        if(isset($param['total_fee']) && !empty($param['total_fee'])) $total_fee=floatval($param['total_fee']*100);//支付金额
        $openid=$param['openid'];
        $out_trade_no=getOrderNum();//订单号
        $pay_type=$param['type'];//支付类型
        $id=$param['id'];//支付物品id

        //引入小程序支付类
        Loader::import('weixinpay.WxcxPay');

        //创建订单
        if($pay_type==1){//1购买会员 2支付快件费 3单个项目4多个项目

            $huiyuan=Member::get($id);//获取申请会员设定
            if(empty($huiyuan)) return mogo_error('会员设定不存在',0);
            if($user['member_type']==0){//非会员申请
                $total_fee=$huiyuan['fee'];
            }else{
                $huiyuan['level_name']=config('member_level')[$huiyuan['level']];
                if($user['member_type']==$param['id']) return mogo_error('您已经是'.$huiyuan['level_name'],0);//已经是该等级会员
                if($user['member_type']>$param['id']) return mogo_error('您申请的会员等级不能低于当前拥有的会员等级',0);
                //当前总费用等于升级会员总费用减去已交会员费，并更新会员注册时间
                $mem=Member::get($user['member_type']);
                $total_fee=$huiyuan['fee']-$mem['fee'];
            }

            $order = Zforder::create([
                "openid" =>$openid,
                "remark" => "购买会员",//支付说明
                "pay_id" => $id,//支付物品id
                "order_sn" => $out_trade_no,//订单号
                "money" => $total_fee,//支付总金额
                "status" => 1,//待支付
            ]);
        }elseif($pay_type==2){//支付快件费用
            $kauijian=Order::get($id);
            if(empty($kauijian)) return mogo_error('您的订单不存在',0);
            if($kauijian['pay_money']<=0) return mogo_error('订单支付金额未确定',0);
//            $danhao=Danhao::get(['is_use'=>0]);
//            if(empty($danhao)) return mogo_error('无可用快递单号',0);
            $total_fee=$kauijian['pay_money'];
            $order = Zforder::create([
                "openid" =>$param['openid'],
                "remark" => "支付寄件费用",//支付说明
                "pay_id" => $param['id'],//支付物品id
                "order_sn" => $out_trade_no,//订单号
                "money" => $total_fee,//支付总金额
                "status" => 1,//待支付
            ]);
        }
        //统一下单
        $appid=config('weiXin')['appid'];//appid
        $secret=config('weiXin')['secret'];//secret
        $mid=config('weiXin')['mid'];//商户号
        $key=config('weiXin')['key'];//商户密钥
//        $total_fee=floatval($total_fee*100);
        $total_fee=floatval(0.01*100);
        if(isset($order)){
            $pay=new \WxcxPay($appid,$openid,$mid,$key,$out_trade_no,$body,$total_fee,$pay_type,$order['id']);
            $res=$pay->pay();
            return mogo_json(['pay'=>$res,'order'=>$order],'统一下单成功',1);
        }else{
            return mogo_error('创建订单失败',0);
        }
    }

    //修改订单状态,小程序支付回调通知
    public function pay_callback()
    {
        $dataOne = array(
            'return_code' => 'SUCCESS',
            'return_msg' => 'OK'
        );
        try {
            $file = 'Weixin.txt';
            $data = file_get_contents('php://input');//接受微信支付结果通知

            if (!$data) {
                logResult('什么都没有返回', $file);
                return;
            }

            $dataOne = $this->arrayToXml($dataOne);

            $string = $data;
            $data = $this->xmlstr_to_array($data);//微信支付通知结果数组
            logResult(json_encode($data));


            if (strcmp($data['return_code'], 'SUCCESS') != 0) ('收到一个失败请求' . $string);
            else logResult('收到成功的请求' . $data['out_trade_no'], $file);

            if ($this->jxSign($data)) {
                logResult('验签成功', $file);
            } else {
                logResult('验签失败', $file);
                echo $dataOne;
                die;
            }

            $order_sn = $data['out_trade_no'];

            if (Zforder::get(["order_sn" => $order_sn])->status != 1) {
                logResult("警告：重复订单处理，可能是微信回调问题", $file);
                throw new Exception("警告：重复订单处理，可能是微信回调问题");
            }
            $attachArray=explode(',',$data['attach']);//返回的拓展参数，如回调url的参数
            $notify_type=$attachArray[0];//1会员支付 2寄快递支付 3单个项目4多个项目
            $orderid=$attachArray[1];//支付id
            $order = Zforder::get($orderid);//获取付款订单
            logResult("订单：".json_encode($order->toArray()));
            //支付成功回调处理
            if($notify_type==1){//购买会员
                $order->update(['status'=>2,'id'=>$order->id]);//更新付款订单状态为已支付
                $mem=MemberModel::get($order['pay_id']);
                User::where(['openid'=>$order->openid])->update([
                    'member_type'=>$mem['level'],//会员等级id
                    'member_time'=>time(),
                ]);
                //计算当前消费用户的上三级获得佣金
//                Brokerage::getParentMoney($order->openid,$order->money);
                logResult('用户id:' . $order->openid . "充值:" . $order->money. "支付购买会员".$order['pay_id'], $file);
            }elseif ($notify_type==2){//寄快递
                $order->update(['status'=>2,'id'=>$order->id]);//更新付款订单状态为已支付
                Order::update([
                    'id'=>$order->pay_id,
                    'is_pay_money'=>1,
                    'order_status'=>3,//已取件
                ]);
                //计算当前消费用户的上三级获得佣金
                $yj=Brokerage::getParentMoney($order->openid,$order->money);
                logResult("佣金：".json_encode($yj));
                logResult('用户id:' . $order->openid . "充值:" . $order->money. "支付快递费" , $file);

            }elseif ($notify_type==3){//单个项目支付



            }elseif ($notify_type==4){//多个项目支付

            }

        } catch (Exception $e) {
            logResult("发生了错误信息：".json_encode($e->getMessage()."".json_encode($e->getData())));
        }

        echo $dataOne;
    }



    //数组转xml
    public function arrayToXml($arr) {
        $xml = "<xml>";
        foreach ($arr as $key => $val) {
            if (is_numeric($val)) {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";

            } else
                $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
        }
        $xml .= "</xml>";
        return $xml;
    }
    //xml转数组
    public function xmlstr_to_array($xmlstr) {
        $doc = new \DOMDocument();
        $doc->loadXML($xmlstr);
        return $this->domnode_to_array($doc->documentElement);
    }

    public function domnode_to_array($node) {
        $output = array();
        switch ($node->nodeType) {
            case XML_CDATA_SECTION_NODE:
            case XML_TEXT_NODE:
                $output = trim($node->textContent);
                break;
            case XML_ELEMENT_NODE:
                for ($i = 0, $m = $node->childNodes->length; $i < $m; $i++) {
                    $child = $node->childNodes->item($i);
                    $v = $this->domnode_to_array($child);
                    if (isset($child->tagName)) {
                        $t = $child->tagName;
                        if (!isset($output[$t])) {
                            $output[$t] = array();
                        }
                        $output[$t][] = $v;
                    } elseif ($v) {
                        $output = (string)$v;
                    }
                }
                if (is_array($output)) {
                    if ($node->attributes->length) {
                        $a = array();
                        foreach ($node->attributes as $attrName => $attrNode) {
                            $a[$attrName] = (string)$attrNode->value;
                        }
                        $output['@attributes'] = $a;
                    }
                    foreach ($output as $t => $v) {
                        if (is_array($v) && count($v) == 1 && $t != '@attributes') {
                            $output[$t] = $v[0];
                        }
                    }
                }
                break;
        }
        return $output;
    }

    //签名校验
    public function jxSign($data) {
        $sign = $data['sign'];

        $file = 'Weixin.txt';
        $data = array_diff_key($data, array_flip(array('sign')));
        ksort($data);
        $string = '';
        foreach ($data as $key => &$value) {
            $string = $string . $key . '=' . $value . '&';
        }
        //count受php版本影响
//        $string = substr($string, 0, count($string) - 2);
        if (strlen($string) > 0) {
            $string = substr($string, 0, strlen($string) - 1);
        }
        $string = $string . '&key=' . config('weiXin')['key'];
        $data['sign'] = strtoupper(md5($string));
        logResult('发送来的：' . $sign . '   ' . '生成的：' . $data['sign'], $file);
        if ($data['sign'] == $sign) return true;

        return false;
    }

}
